package com.dduggs.note.util;


import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 封装分页数据
 */
public class PageUtil {

    /**
     * 封装分页数据
     * @param pageNo    页号
     * @param pageSize  每页数量
     * @return  分页数据
     */
    public<T> Map<String , Object> getPages(int pageNo, int pageSize, Page<T> rs){

        Boolean first = false;                              //是否为首页
        Boolean last = false;                               //是否为尾页
        int number = pageNo;                                //当前页号
        int totalElements = (int) rs.getTotalElements();       //总记录数
        List<T> content = rs.getContent();                     //内容
        int totalPages = 0;                                 //总页数
        if(pageSize > 0) {
            if((totalElements % pageSize) == 0){
                totalPages = totalElements/pageSize;
            }else{
                totalPages = (totalElements/pageSize)+1;
            }
        }

        if(number == 0){
            first = true;   //当前页号为0,为首页
        }
        if(number == (totalPages-1)){
            last = true;    //当前页号等于总页数,为尾页
        }
        Map<String, Object> map = new HashMap<>();
        map.put("first", first);
        map.put("last", last);
        map.put("number", number);
        map.put("pageSize", pageSize);
        map.put("totalPages", totalPages);
        map.put("totalElements", totalElements);
        map.put("content", content);
        return map;
    }

    /**
     * 分装分页数据
     *
     * @param list 所有数据的集合
     * @param page 页码
     * @param rows 条数
     * @return 分页数据
     */
    public Page getPages(int page, int rows, List list){

        List resultList = new ArrayList<>();
        int endNum;
        int totalPage = list.size()%rows == 0 ? list.size()/rows : list.size()/rows+1;
        if(page>0 && page<=totalPage && rows>0) {
            if(rows > list.size())
                rows = list.size();
            if (page == totalPage)
                endNum = list.size();
            else
                endNum = page * rows;
            for (int i = (page - 1) * rows; i < endNum; i++) {
                resultList.add(list.get(i));
            }
        }
        Pageable pageable = new PageRequest(page-1, rows);
        return new PageImpl(resultList, pageable, list.size());
    }

}
